package drds.server.execute_engine;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import drds.server.Server;

public class Tasks {

	private ConcurrentHashMap<Integer, Task> runningTaskMap = new ConcurrentHashMap<Integer, Task>();
	private ConcurrentLinkedQueue<Task> waitingTaskQueue = new ConcurrentLinkedQueue<Task>();
	private volatile boolean noMoreTaskInput = false;

	public void addTask(Task task, boolean rightNowTrueOrAddToQueueFalse) {

		if (rightNowTrueOrAddToQueueFalse) {
			runTask(task);
		} else {
			waitingTaskQueue.offer(task);
			if (runningTaskMap.isEmpty()) {
				task = waitingTaskQueue.poll();
				if (task != null) {
					runTask(task);
				}
			}
		}
	}

	public void setNoMoreTaskInput() {
		this.noMoreTaskInput = true;
	}

	private void runTask(Task task) {
		runningTaskMap.put(task.getId(), task);
		Server.getInstance().getBusinessExecutor().execute(task);
	}

	public boolean taskFinished(Task task) {
		if (task == null) {
			throw new NullPointerException("task");
		}
		runningTaskMap.remove(task.getId());
		task = waitingTaskQueue.poll();
		if (task != null) {
			runTask(task);
			return false;
		} else {
			if (noMoreTaskInput) {
				return runningTaskMap.isEmpty() && waitingTaskQueue.isEmpty();
			} else {
				return false;
			}
		}

	}
}
